
package com.studiofortress.sf.audio;

import com.studiofortress.sf.util.Resource;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * A type of player designed for building wav files.
 * 
 * @author Joseph Lenton - JosephLenton@StudioFortress.com
 */
public class WavPlayer extends BufferedAudioPlayer
{
    /**
     * Creates a new WavPlayer loading the audio from the given url.
     * @param url The Wav file to play.
     */
    public WavPlayer(String url)
    {
        this( Resource.getStream(url) );
    }

    /**
     * This will use the given stream as it's source for the data for it's audio
     * file.
     * @param stream A stream to read the wav file from.
     */
    public WavPlayer(InputStream stream)
    {
        super( new WavAudioStreamFactory(stream) );
    }

    private static class WavAudioStreamFactory implements AudioStreamFactory
    {
        private final AudioBuffer buffer;

        public WavAudioStreamFactory(InputStream input)
        {
            buffer = new DynamicAudioBuffer();
            new AudioLoader( input, buffer ).start();
        }
        
        public AudioInputStream newStream()
        {
            try {
                return AudioSystem.getAudioInputStream( new CachingInputStream(buffer) );
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            } catch (UnsupportedAudioFileException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
